# -*- coding: utf-8 -*-
from xTkinter import *
import tkFileDialog
import tkMessageBox as msgBox
import sys
from RequeteSQL import *
from RequeteSQL import *
RequeteSQL = RequeteSQL()
import xmlrpclib
from Validation_Contraintes import *

class VueSaisieChamps(Frame):
    def __init__(self,master,parent,**cnf):
        self.ListeChamps=[]
        self.ListEntries=[]
        self.ListLabels=[]
        self.ListeContraintes = []
        self.ListeType = []
        self.ListeLongueur = []
        self.ListePrecision = []
        self.ListeScale = []
        self.parent = parent
        self.master=master
        Frame.__init__(self,master,cnf)             
        self.pack(side=LEFT,anchor=NW)
        self.configure(width=800,height=600)        
        self.Bouton=xButton(self,text="Ajouter",width=12, command=self.ajouterData)
        self.Bouton.setLocation(0,0)
        self.CBTables=xCombobox(self)
        self.CBTables.setLocation(135,0)
        self.CBTables.setWidth(15)
        self.CBTables.setListWidth(25)
        self.CBTables.setListHeight(5)
        self.obtenirTables() 
        self.CBTables.setValidator(self.obtenirChamps)
        self.CBTables.setText('<Choisir>')
        self.Validateur =  ValidationContrainte()
        
    def ajouterData(self):
        Valeurs = {}
        Valide = 1
        for i in range(len(self.ListeChamps)):
            if(self.ListeType[i] == 'DATE'):
                if not self.Validateur.validerDate(self.ListEntries[i].getText()):
                    msgBox.showerror('Saisie de données',"Le champ "  + self.ListeChamps[i][0] + " est de type date\nIl doit être de format jj/mm/aa\n"+self.ListEntries[i].getText() )
                    return
            if(self.ListeType[i] == 'NUMBER'):
                if(self.ListePrecision ==0):
                    if not self.Validateur.validerEntier(self.ListEntries[i].getText()):
                        msgBox.showerror('Saisie de données',"Le champ "  + self.ListeChamps[i][0] + " doit etre un nombre entier" )
            if (self.ListeType[i] == 'NUMBER' and self.ListeScale[i] ==0):
                Valeurs[self.ListeChamps[i][0]] = self.ListEntries[i].getText()+ ",0"
            else:
                 Valeurs[self.ListeChamps[i][0]] = self.ListEntries[i].getText()
            for contraintes in self.ListeContraintes:
                
                if contraintes["ATTRIBUT_GAUCHE"] == self.ListeChamps[i][0]:
                    print "UNMEEE"
                    fonction = self.Validateur.Operande[contraintes['COMPARAISON']]
                    if (fonction(int(self.ListEntries[i].get()),int(contraintes['OPERANDE_DROITE'])) == 0):
                        msgBox.showerror('Saisie de données',contraintes['MESSAGE_ERREUR'] )
                        Valide = 0
        if (Valide == 1):
            print Valeurs
            Reponse = self.parent.serveur.InsererEnregistrement(self.CBTables.getText(), Valeurs)
            if Reponse[0]==1:
                Reponse = self.parent.serveur.ExecuterRequeteSQL('commit')
                if Reponse[0]==1:
                    msgBox.showinfo('PERP | Ajout d\'enregistrements', 'Ajout d\'enregistrements reussit')
                else: 
                    msgBox.showinfo('PERP | Ajout d\'enregistrements', 'Erreur ' + Reponse[1])
            else:
                msgBox.showinfo('PERP | Ajout d\'enregistrements', 'Erreur ' + Reponse[1])
            pass

    def obtenirTables(self):
        Reponse = self.parent.serveur.ObtenirListeTables(self.parent.user,self.parent.profil)
        if(Reponse[0]==1):
            self.ListeChamps = Reponse[1]
            for i in range(len(self.ListeChamps)):
                self.CBTables.addItem(self.ListeChamps[i][0])
                self.CBTables.setText(self.ListeChamps[i][0])
        
    def obtenirChamps(self):
        self.ListeChamps=[]
        for i in range(len(self.ListEntries)):
            self.ListEntries[i].destroy()
            self.ListLabels[i].destroy()

        self.ListEntries=[]
        self.ListLabels=[]
        self.ListeContraintes = []
        table=self.CBTables.getText();
        Requete="SELECT COLUMN_NAME,DATA_TYPE,DATA_LENGTH,DATA_PRECISION,DATA_SCALE FROM USER_TAB_COLUMNS WHERE LOWER(TABLE_NAME)='"+table.lower()+"'"
        Reponse = self.parent.serveur.ExecuterRequeteSQLWhere(Requete)
        if(Reponse[0]==1):
            self.ListeChamps = Reponse[1]
            for i in range(len(self.ListeChamps)):
                self.ListLabels.append(xLabel(self,text=self.ListeChamps[i][0], width=len(self.ListeChamps[i][0])+2, anchor=SW ))
                self.ListLabels[len(self.ListLabels)-1].setLocation(0,(i+1)*25+5)
            for i in range(len(self.ListeChamps)):
                self.ListEntries.append(xEntry(self,width=self.ListeChamps[i][2]))
                self.ListEntries[len(self.ListEntries)-1].setLocation(120,(i+1)*25+5)
                self.ListeType.append(self.ListeChamps[i][1])
                self.ListeLongueur.append(self.ListeChamps[i][2])
                self.ListePrecision.append(self.ListeChamps[i][3])
                self.ListeScale.append(self.ListeChamps[i][4])
                #print self.ListeChamps[i][0], self.ListeChamps[i][1], self.ListeChamps[i][2], self.ListeChamps[i][3], self.ListeChamps[i][4]
                print self.ListeChamps[i][0]," ",  self.ListeChamps[i][1]," ",self.ListeChamps[i][2], " ",self.ListeChamps[i][3], " ", self.ListeChamps[i][4]
            Reponse = self.parent.serveur.ObtenirContraintes(self.CBTables.getText())
            if(Reponse[0]==1):
                  self.ListeContraintes = Reponse[1]
        else:
          msgBox.showerror('PERP 2009 | Édition des tables', 'Une erreur est survenue!\n'+Reponse[1])
          
    def close(self):
        self.destroy()
        pass        
    

            
#
#
#class Controleur:
#    def __init__(self):
#        self.user = "ADMIN"
#        self.profil = "ADMIN"
#        Serveur='http://localhost:8000'
#        self.serveur=xmlrpclib.ServerProxy(Serveur)
#        root=Tk()
#        root.geometry('1200x600')
#        vi=VueSaisieChamps(root,self)
#        root.mainloop()       
#
#Controleur = Controleur()

    
    
    
